﻿
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Redis
{
    /// <summary>
    /// redis 的客户端封装<br />
    /// https://github.com/StackExchange/StackExchange.Redis/blob/master/Docs/Basics.md
    /// </summary>
    public class RedisCache
    {
        private static Lazy<ConnectionMultiplexer> _lazyConnection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisCache"]));

        public static ConnectionMultiplexer Connection { get { return _lazyConnection.Value; } }
    }

    /// <summary>
    /// rediscache 的扩展
    /// </summary>
    public static class RedisCacheExtension
    {
        /// <summary>
        /// 对hash的操作
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="acquirer"></param>
        /// <returns></returns>
        public static HashEntry[] HashGetAll(this IDatabase cache, StackExchange.Redis.RedisKey key, Func<HashEntry[]> acquirer)
        {
            if (!cache.KeyExists(key))
            {
                var hashFields = acquirer();
                cache.HashSet(key, hashFields);
            }
            return cache.HashGetAll(key);
        }

        /// <summary>
        /// 对string的操作
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="acquirer"></param>
        /// <returns></returns>
        public static RedisValue StringGet(this IDatabase cache, StackExchange.Redis.RedisKey key, Func<RedisValue> acquirer, TimeSpan? expiry = null)
        {
            if (!cache.KeyExists(key))
            {
                var result = acquirer();
                if (expiry != null)
                {
                    cache.StringSet(key, result, expiry);
                }
                else
                {
                    cache.StringSet(key, result);
                }
            }
            return cache.StringGet(key);
        }

        /// <summary>
        /// 对list的操作
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="acquirer"></param>
        /// <returns></returns>
        public static RedisValue[] ListRange(this IDatabase cache, StackExchange.Redis.RedisKey key, Func<RedisValue[]> acquirer)
        {
            if (!cache.KeyExists(key))
            {
                var result = acquirer();
                cache.ListRightPush(key, result);
            }
            return cache.ListRange(key);
        }
    }
}
